﻿using SharpCompress.Archive;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace November {
    class ArchiveModel : INovModel {
        private IArchive Archive { get; set; }
        private List<IArchiveEntry> EntryList { get; set; }
        private Int32 Index { get; set; }

        public ArchiveModel(String archiveFileName) {
            Archive = ArchiveFactory.Open(new FileStream(archiveFileName, FileMode.Open));
            EntryList = Archive.Entries.Where(x => Utility.ImageFilter(x.FilePath)).ToList();
            EntryList.Sort(new ArchiveEntryComparer());
            Index = 0;
        }

        ~ArchiveModel() {
            Archive.Dispose();
        }

        public Image GetImage() {
            using (Stream imageStream = EntryList[Index].OpenEntryStream()) {
                return Image.FromStream(imageStream);
            }
        }

        public String GetImageName() {
            return EntryList[Index].FilePath;
        }

        public Int32 GetImageIndex() {
            return Index + 1;
        }

        public Int32 GetImageCount() {
            return EntryList.Count;
        }

        public Boolean FirstImage() {
            return Index != (Index = 0);
        }

        public Boolean EarlierImage() {
            Func<IArchiveEntry, String> map = x => x.FilePath.Substring(0, x.FilePath.LastIndexOf('/'));
            IIndexed<String> list = new MappedList<IArchiveEntry, String>(EntryList, map);
            return Index != (Index = Utility.FindEarlier(list, Index));
        }

        public Boolean PreviousImage() {
            Index = (Index + GetImageCount() - 1) % GetImageCount();
            return GetImageCount() != 1;
        }

        public Boolean NextImage() {
            Index = (Index + 1) % GetImageCount();
            return GetImageCount() != 1;
        }

        public Boolean LaterImage() {
            Func<IArchiveEntry, String> map = x => x.FilePath.Substring(0, x.FilePath.LastIndexOf('/'));
            IIndexed<String> list = new MappedList<IArchiveEntry, String>(EntryList, map);
            return Index != (Index = Utility.FindLater(list, Index));
        }

        public Boolean LastImage() {
            return Index != (Index = GetImageCount() - 1);
        }

        public Boolean SortBy(SortMode mode) {
            return false;
        }
    }
}
